package com.jsh.erp.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.core.parser.SqlParserHelper;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.jsh.erp.utils.Tools;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Configuration
public class TenantConfig {

    @Bean
    public ISqlParser tenantSqlParser() {
        TenantSqlParser tenantSqlParser = new TenantSqlParser() {
            //解决多租户 Column 'tenant_id' specified twice
            @Override
            public void processInsert(Insert insert) {
                if (getTenantHandler().doTableFilter(insert.getTable().getName())) {
                    // 过滤退出执行
                    return;
                }
                if (isAleadyExistTenantColumn(insert)) {
                    return;
                }
                insert.getColumns().add(new Column(getTenantHandler().getTenantIdColumn()));
                if (insert.getSelect() != null) {
                    processPlainSelect((PlainSelect) insert.getSelect().getSelectBody(), true);
                } else if (insert.getItemsList() != null) {
                    // fixed github pull/295
                    ItemsList itemsList = insert.getItemsList();
                    if (itemsList instanceof MultiExpressionList) {
                        ((MultiExpressionList) itemsList).getExprList().forEach(el -> el.getExpressions().add(getTenantHandler().getTenantId()));
                    } else {
                        ((ExpressionList) insert.getItemsList()).getExpressions().add(getTenantHandler().getTenantId());
                    }
                } else {
                    throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId");
                }
            }

            /**
             * 判断是否存在租户id列字段
             * @param insert
             * @return 如果已经存在，则绕过不执行
             */
            private boolean isAleadyExistTenantColumn(Insert insert) {
                List<Column> columns = insert.getColumns();
                if (CollectionUtils.isEmpty(columns)) {
                    return false;
                }
                String tenantIdColumn = getTenantHandler().getTenantIdColumn();
                return columns.stream().map(Column::getColumnName).anyMatch(tenantId -> tenantId.equals(tenantIdColumn));
            }
        };
        tenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
            public Expression getTenantId() {
                RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                String token = request.getHeader("X-Access-Token");
                Long tenantId = Tools.getTenantIdByToken(token);
                if (tenantId != 0L) {
                    return new LongValue(tenantId);
                } else {
                    //超管
                    return null;
                }
            }

            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            @Override
            public boolean doTableFilter(String tableName) {
                RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                //获取开启状态
                Boolean res = true;
                String token = request.getHeader("X-Access-Token");
                Long tenantId = Tools.getTenantIdByToken(token);
                if (tenantId != 0L) {
                    // 这里可以判断是否过滤表
                    if ("jsh_material_property".equals(tableName) || "jsh_sequence".equals(tableName)
                            || "jsh_user_business".equals(tableName) || "jsh_function".equals(tableName)
                            || "jsh_platform_config".equals(tableName) || "jsh_tenant".equals(tableName)) {
                        res = true;
                    } else {
                        res = false;
                    }
                }
                return res;
            }
        });

        return tenantSqlParser;
    }

    /**
     * 这里最好用代理这样可以多重操作
     *
     * @return
     */
    @Bean
    public ISqlParserFilter tenantSqlParserFilter() {
        return new ISqlParserFilter() {
            @Override
            public boolean doFilter(MetaObject metaObject) {
                MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
                // 过滤自定义查询此时无租户信息约束出现
                if ("com.jsh.erp.datasource.mappers.UserMapperEx.getUserListByUserNameOrLoginName".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.datasource.mappers.UserMapperEx.disableUserByLimit".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.datasource.mappers.RoleMapperEx.getRoleWithoutTenant".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.datasource.mappers.LogMapperEx.insertLogWithUserId".equals(ms.getId())) {
                    return true;
                }
                return false;
            }
        };
    }


    /**
     * 性能分析拦截器，不建议生产使用
     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor(){
//        return new PerformanceInterceptor();
//    }


}
